<template>
  <div class="chat">

    <!-- 这个左侧的列表 -->
    <div class="chat-left-content">
      <div style="width: 1px;height: 6px"></div>
      <div v-for="item in conversationList" :class="item.userId == to_username? 'user-item-checked': 'user-item-normal'" @click="changeTalkUser(item)" style="width: 100%; height: 50px; text-align: center;margin-bottom: 1px;cursor: pointer;">
        <div style="display: flex; flex-direction: row; width: 100%; align-items: center; margin-left: 10px">
          <img width="22px" height="22px; " style="border-radius: 50%; margin-right: 10px" :src="item.userImageUrl"/>
          <p>{{item.userName}}</p>
          <p style="background: red; border-radius: 50%; margin-top: -3px; color: white; margin-left: 5px; height: 5px; width: 5px" v-if="conversationListReadStatus[item.userId]"></p>
        </div>
      </div>
    </div>

    <div class="chat-right-content">

      <div class="chat-content">

        <div class="name-label">
          <p>{{contactUser.customerNickName}}</p>
        </div>

        <div style="overflow: auto; height: 360px; background: #f6f7f8;padding: 5px;-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;" ref="contents">
          <div :class="item.from == from_username ? 'msg-group-right' : 'msg-group-left'" style="margin-bottom: 20px"
               v-for="item in chatHistory">

              <div :class="item.from == from_username ? 'msg-group-left' : 'msg-group-right'">

                <p :class="item.from == from_username ? 'text-right' : 'text'" v-if="isChatTextType(item)"  v-html="handleMsg(item)"></p>
                <img :class="item.from == from_username ? 'text-right' : 'text'"  width="80px" :height="(80 * item.height)/item.width" v-if="item.isPic === 1" :src="item.sourceMsg"/>

                <!--<div class="user-card" v-if="isUserCardType(item)">-->
                  <!--fffffff-->
                <!--</div>-->

                <div class="goods-card" @click="ImCardClick(2,item.ext.goodsId)" v-if="isGoodsCardType(item)">
                  <div class="goods-card-content">

                    <img :src="item.ext.goodsAvatar">
                    <div style="margin-left: 10px;">
                      <span style="text-overflow: ellipsis;">{{item.ext.goodsName}}</span>
                    </div>
                  </div>

                  <div style="width: 100%; height: 1px; background: #f5f6f7;"></div>

                  <span style="margin-bottom: 8px; margin-top: 8px ;margin-left: 10px; color: #888888">汇美产品</span>

                </div>


                <p style="width: 12px;height: 12px;"></p>

                <img width="32px" height="32px; " style="border-radius: 50%;cursor: pointer;" @click="avatarClick(item)" :src="item.fromAvatar"/>

              </div>

          </div>

        </div>

      </div>

      <div class="input-content" >
        <div style="width: 100%; height: 40px;" class="action-label">

          <div class="chat-ops-icon ib">
            <div class="ib">
              <a class="adropdown-trigger" @click="showEmoji = !showEmoji">
                <i class="iconfont icon-biaoqing2" style="color: rgba(0, 0, 0, 0.65);"></i>
                <ul class="faces-ul" v-show="showEmoji">
                  <li v-for="(value,key) in emojiMap" :key="key" @click="clickFace(key)" class="webim-emoji-item">
                    <img :src="value" alt="emoj"/>
                  </li>
                </ul>
              </a>
            </div>
          </div>

          <label class="chat-ops-icon ib" @click="toSendPic">
            <i class="iconfont icon-tupian"></i>
          </label>
          <input id="picInput" type="file" hidden="true" @change="sendPrivateFile"/>
          <label class="chat-ops-icon ib" @click="clearChat">
            <i class="iconfont icon-shanchu"></i>
          </label>
        </div>
        <input type="text" placeholder="输入消息" id="inputcontent" @keyup.enter="sendTextMsg()" class="input-txt">
        <div style="text-align: right;margin-bottom: 5px;margin-right: 5px;">
          <span class="btn-close" @click="closeChat()">关闭</span>
          <span class="btn-close" @click="sendTextMsg()">发送</span>
        </div>
      </div>

    </div>

    <div class="chat-detail-content" v-if="detailStatus==1">

      <div class="chat-detail-title">
        <div>
          <p>用户信息</p>
          <span></span>
        </div>
        <div>
        </div>
      </div>

      <div class="item-user-detail">

        <img class="item-avatar" :src="contactUser.imageUrl"/>

        <p>{{contactUser.customerNickName}}</p>

        <div class="info-item">
          <p>手机号</p>
          <p class="item-value">{{contactUser.tel}}</p>
        </div>
        <div class="info-item">
          <p>身份证号</p>
          <p class="item-value">{{contactUser.cardId}}</p>
        </div>
        <div class="info-item">
          <p>地区</p>
          <p class="item-value">{{contactUser.chooseProvinceName }} - {{contactUser.chooseCityName}} </p>
        </div>
        <div class="info-item">
          <p>性别</p>
          <p class="item-value">{{contactUser.sex == 1?'女性': '男性'}}  </p>
        </div>

      </div>

    </div>
    <div class="chat-detail-content" v-if="detailStatus==2">

      <div class="chat-detail-title">
        <div>
          <p>商品信息</p>
          <span></span>
        </div>
        <div>
        </div>
      </div>

      <div class="item-user-detail">

        <img class="item-goods" :src="goodsDetailInfo.goodsImageOneUrl"/>

        <p>{{goodsDetailInfo.goodsName}}</p>

        <div class="goods-item">
          <p>门市价格</p>
          <p class="item-value" style="color: red;">￥{{goodsDetailInfo.retailPrice}}</p>
        </div>
        <div class="goods-item">
          <p>平台价格</p>
          <p class="item-value" style="color: red;">￥{{goodsDetailInfo.platformPrice}}</p>
        </div>

        <div class="goods-item">
          <p>预约金</p>
          <p class="item-value" style="color: red;">￥{{goodsDetailInfo.onlinePay}}  </p>
        </div>

        <div class="goods-item">
          <p>所属医院</p>
          <p class="item-value">{{goodsDetailInfo.institutionName}}  </p>
        </div>

        <div class="goods-item">
          <p>库存</p>
          <p class="item-value">{{goodsDetailInfo.surplusNum}}  </p>
        </div>

      </div>

    </div>


  </div>
</template>

<script>
  //  import axios from 'axios'
  //  import { userPersonal } from '../../http/getDate'
  import ee_1 from '../../assets/faces/ee_1.png'
  import ee_2 from '../../assets/faces/ee_2.png'
  import ee_3 from '../../assets/faces/ee_3.png'
  import ee_4 from '../../assets/faces/ee_4.png'
  import ee_5 from '../../assets/faces/ee_5.png'
  import ee_6 from '../../assets/faces/ee_6.png'
  import ee_7 from '../../assets/faces/ee_7.png'
  import ee_8 from '../../assets/faces/ee_8.png'
  import ee_9 from '../../assets/faces/ee_9.png'
  import ee_10 from '../../assets/faces/ee_10.png'
  import ee_11 from '../../assets/faces/ee_11.png'
  import ee_12 from '../../assets/faces/ee_12.png'
  import ee_13 from '../../assets/faces/ee_13.png'
  import ee_14 from '../../assets/faces/ee_14.png'
  import ee_15 from '../../assets/faces/ee_15.png'
  import ee_16 from '../../assets/faces/ee_16.png'
  import ee_17 from '../../assets/faces/ee_17.png'
  import ee_18 from '../../assets/faces/ee_18.png'
  import ee_19 from '../../assets/faces/ee_19.png'
  import ee_20 from '../../assets/faces/ee_20.png'
  import ee_21 from '../../assets/faces/ee_21.png'
  import ee_22 from '../../assets/faces/ee_22.png'
  import ee_23 from '../../assets/faces/ee_23.png'
  import ee_24 from '../../assets/faces/ee_24.png'
  import ee_25 from '../../assets/faces/ee_25.png'
  import ee_26 from '../../assets/faces/ee_26.png'
  import ee_27 from '../../assets/faces/ee_27.png'
  import ee_28 from '../../assets/faces/ee_28.png'
  import ee_29 from '../../assets/faces/ee_29.png'
  import ee_30 from '../../assets/faces/ee_30.png'
  import ee_31 from '../../assets/faces/ee_31.png'
  import ee_32 from '../../assets/faces/ee_32.png'
  import ee_33 from '../../assets/faces/ee_33.png'
  import ee_34 from '../../assets/faces/ee_34.png'
  import ee_35 from '../../assets/faces/ee_35.png'
  import { mapGetters, mapActions } from "vuex"
  import {getStorage} from "@/utils/auth";
  import * as stn from "@/constants/storeName";

  export default {
    name: 'Chat',
    data() {
      return {
        from_username: '6049', // url中的发起方用户名  user004
        to_username: '', // url中的接收方用户名
        conn: {}, // 与环信的通信长连接
        chatHistory: [], // 聊天记录数组
        currentUserpwd: '88888888', // 当前用户环信密码  a123456
        accence_token: '', // 权限token
        emojiMap: {
          '[):]': ee_1,
          '[:D]': ee_2,
          '[;)]': ee_3,
          '[:-o]': ee_4,
          '[:p]': ee_5,
          '[(H)]': ee_6,
          '[:@]': ee_7,
          '[:s]': ee_8,
          '[:$]': ee_9,
          '[:(]': ee_10,
          '[:\'(]': ee_11,
          '[:|]': ee_12,
          '[(a)]': ee_13,
          '[8o|]': ee_14,
          '[8-|]': ee_15,
          '[+o(]': ee_16,
          '[<o)]': ee_17,
          '[|-)]': ee_18,
          '[*-)]': ee_19,
          '[:-#]': ee_20,
          '[:-*]': ee_21,
          '[^o)]': ee_22,
          '[8-)]': ee_23,
          '[(|)]': ee_24,
          '[(u)]': ee_25,
          '[(S)]': ee_26,
          '[(*)]': ee_27,
          '[(#)]': ee_28,
          '[(R)]': ee_29,
          '[({)]': ee_30,
          '[(})]': ee_31,
          '[(k)]': ee_32,
          '[(F)]': ee_33,
          '[(W)]': ee_34,
          '[(D)]': ee_35
        }, // 表情集合
        showEmoji: false, // 是否显示表情
        toNickName: '', //接收人昵称
        toHeadImg: '', //接收人头像
        toAccountType: '', // 接收人类型
        fromNickName: '', // 发送人昵称
        fromHeadImg: '', // 发送人头像
        fromAccountType: '', // 发送人类型
        sendType: '', // 发送类型
        conversationList: [], //聊天记录列表
        conversationListReadStatus: {}, // 记录是否有未读消息
        contactUser: {},//用户信息
        showUserInfo: true,
        goodsDetailInfo: {},
        detailStatus: 1, // 1:用户资料 2: 商品名片
      }
    },
    props:{
      contactId: {
        type: String,
        default:() => "0"
      },


    },
    watch:{
      conversationListReadStatus:{
        handler(val, oldVal){
          let count = 0;
          for (item in val){
            if (item){
              count++;
            }
          }
          console.log(count+"<-----");
        },
        deep:true
      }
    },
    computed: {
      ...mapGetters({
          userInfo: "getUserInfo"
        }
      )/*,
      getMyNickName() {
        return this.myNickName
      }*/
    },
    created() {
      let userInfo = getStorage(stn.USER_INFO);

      var params = this.$route.params;
      this.to_username = this.contactId;
      this.toNickName = "ttt";
      this.toHeadImg = "http://cactus-pro.oss-cn-hangzhou.aliyuncs.com/web_images/Goods/155494720512.png";
      this.toAccountType = 1;  // 后台网页聊天，都是跟普通用户聊
      this.fromAccountType = "3";   // 后台登录者的类型，目前只有客服和代理可以通过后台聊天
      //console.log(params.id+"---"+this.toNickName+"-----"+this.toHeadImg+"----"+this.fromAccountType)
      if (this.fromAccountType == 3){ // 客服
        if (userInfo){
          this.fromHeadImg = userInfo.imAvatar;
          this.fromNickName = userInfo.imName;
          this.from_username = userInfo.imId;
        }
        // var adminId = this.userInfo.id
        // this.from_username = '6049'
        // this.fromNickName = '客服'+adminId
        // this.fromHeadImg = 'http://cactus-pro.oss-cn-hangzhou.aliyuncs.com/web_images/Goods/155494720512.png'
      }else if (this.fromAccountType == 2) { // 代理

      }
    },
    mounted() {
      if (!this.to_username){
        this.to_username = sessionStorage.getItem("lastContactUser");
      }
      this.loginEasemob();
      this.getContactUserInfo();
      this.getChatListDataFromLocal();
      this.getConversationList();



    },
    methods: {
      // 登录环信
      loginEasemob() {
        this.$imoption.user = this.from_username
        this.$imoption.pwd = this.currentUserpwd
        this.$imoption.success = (res) => {
          this.accence_token = res.access_token
          //this.myNickName = res.user.nickname
          this.addListen()
        }
        this.$imconn.open(this.$imoption)
      },
      addListen() {
        this.$imconn.listen({
          onOpened: function (message) {
            console.log('用户已上线')
          },
          onClosed: function (message) {
            console.log('用户已下线')
          },
          onEmojiMessage: this.receiveEmojiMessage,
          onPictureMessage: this.receivePictureMessage,
          onTextMessage: this.receiveTextMsg
        })
      },
      // 从环信服务器获取聊天历史记录
      getChatHistortData() {
        axios.get('http://a1.easemob.com/1106190531107258/tonglianyimei/chatmessages', {
          params: {
            org_name: '1106190531107258',
            app_name: 'tonglianyimei',
            Authorization: `Bearer ${this.accence_token}`
          }
        }).then((val) => {
          console.log(JSON.stringify(val))
        }).catch(error => {

        })
      },
      // 接受文本消息
      // 从localstroage获取聊天历史记录
      getChatListDataFromLocal() {
        var chatData = JSON.parse(localStorage.getItem('chatData'))
        if (chatData) {
          this.chatHistory = [];
          var currentChatData = chatData.chatHistoryData[this.to_username];
          if (currentChatData) {
            this.chatHistory.push(...currentChatData)
          }
        }else{
          let chatHistoryData = {};
          chatHistoryData[this.to_username] = [];
          localStorage.setItem('chatData', JSON.stringify({chatHistoryData}))
        }
        this.getConversationList();
        this.scrollToBottom();
      },

      getConversationList(){
        let data = JSON.parse(localStorage.getItem('chatData')).chatHistoryData;
        let customersIds = "";
        for (let key in data){
          // this.conversationList.push(key);
          customersIds += key+",";
        }
        customersIds = customersIds.substring(0,customersIds.length-1);
        // this.conversationList.push(key);
        if (customersIds){
          this.$Get(this.$Config.api.getCustomersInfo, {
            ids: customersIds
          }).then(res => {
            this.conversationList = [];
            this.conversationList = res.data;
          });
        }

      },

      changeTalkUser(item){
        if (item.customerId != this.to_username) {
          this.to_username = item.userId;
          this.conversationListReadStatus[item.userId] = false;
          this.chatHistory = [];
          this.getContactUserInfo();
          this.getChatListDataFromLocal();
          this.detailStatus = 1;
        }
      },

      // 接受文本消息
      receiveTextMsg(message) {
        let _this = this;
        let _thisChatHistory = this.chatHistory;
        let sendTimeWZ = message.time ? new Date(message.time) : new Date()
        let sendTime = sendTimeWZ.getMonth() + 1 + '-' + sendTimeWZ.getDate() + ' ' + sendTimeWZ.getHours() + ':' + sendTimeWZ.getMinutes()
        let receiveMessage = {
          from: message.from,
          fromAvatar: message.ext.fromAvatar,
          fromNickName: message.ext.fromNickName,
          sourceType: message.ext.dataType,
          //sourceType:'text',       这里不能写默认值，如果写了，后面用到这个模型，sourceTyped的值一直为text
          sourceMsg: message.data,
          isPic: 0,
          time: sendTime
        };
        if (message.ext){
          receiveMessage.ext = message.ext;
        }

        let to_username = message.from;
        var chatData = JSON.parse(localStorage.getItem('chatData'));
        if (chatData) {
          if (to_username in chatData.chatHistoryData){
            chatData.chatHistoryData[to_username].push(receiveMessage);
            localStorage.setItem('chatData', JSON.stringify(chatData))
          } else{
            let list = [];
            list.push(receiveMessage);
            chatData.chatHistoryData[to_username] = list;
            localStorage.setItem('chatData', JSON.stringify(chatData))
          }

        } else {
          let chatHistoryData = {};
          chatHistoryData[to_username] = [receiveMessage];
          localStorage.setItem('chatData', JSON.stringify({chatHistoryData}))
        }
        if (to_username == this.contactUser.customerId){
          _thisChatHistory.push(receiveMessage);
        }else{
          _this.conversationListReadStatus[to_username] = true;
        }
        _this.getConversationList();
        console.log('get Msg---->');
        sessionStorage.setItem("lastContactUser",message.from);
        _this.$emit('onGotMsg','');
        _this.scrollToBottom();
      },
      // 接受表情消息 -- >
      receiveEmojiMessage(message) {

        let sendTimeWZ = message.time ? new Date(message.time) : new Date()
        let sendTime = sendTimeWZ.getMonth() + 1 + '-' + sendTimeWZ.getDate() + ' ' + sendTimeWZ.getHours() + ':' + sendTimeWZ.getMinutes()
        let receiveMessage = {
          from: message.from,
          fromAvatar: message.ext.fromAvatar,
          fromNickName: message.ext.fromNickName,
          sourceType: 'emo',
          sourceMsg: message.data,
          time: sendTime,
          isPic: 0
        }
        //let to_username = this.to_username
        let to_username = message.from
        var chatData = JSON.parse(localStorage.getItem('chatData'))
        if (chatData) {
          if (to_username in chatData.chatHistoryData){
            chatData.chatHistoryData[to_username].push(receiveMessage);
            localStorage.setItem('chatData', JSON.stringify(chatData))
          } else{
            let list = [];
            list.push(receiveMessage);
            chatData.chatHistoryData[to_username] = list;
            localStorage.setItem('chatData', JSON.stringify(chatData))
          }
        } else {
          let chatHistoryData = {}
          chatHistoryData[to_username] = [receiveMessage]
          localStorage.setItem('chatData', JSON.stringify({chatHistoryData}))
        }
        if (to_username == this.contactUser.customerId) {
          this.chatHistory.push(receiveMessage)
        }else{
          this.conversationListReadStatus[to_username] = true;
        }
        this.scrollToBottom();
        // this.chatHistory.push(message)
        this.getConversationList();

      },
      // 接受图片消息
      receivePictureMessage(message) {
        console.log("img=------")
        console.log(JSON.stringify(message))

        let sendTimeWZ = message.time ? new Date(message.time) : new Date()
        let sendTime = sendTimeWZ.getMonth() + 1 + '-' + sendTimeWZ.getDate() + ' ' + sendTimeWZ.getHours() + ':' + sendTimeWZ.getMinutes()
        let receiveMessage = {
          from: message.from,
          fromAvatar: message.ext.fromAvatar,
          fromNickName: message.ext.fromNickName,
          sourceType: message.ext.dataType,
          sourceMsg: message.url,
          width: message.width,
          height: message.height,
          time: sendTime,
          isPic: 1
        }

        console.log(JSON.stringify(receiveMessage))

        //let to_username = this.to_username
        let to_username = message.from
        var chatData = JSON.parse(localStorage.getItem('chatData'))
        if (chatData) {
          if (to_username in chatData.chatHistoryData){
            chatData.chatHistoryData[to_username].push(receiveMessage);
            localStorage.setItem('chatData', JSON.stringify(chatData))
          } else{
            let list = [];
            list.push(receiveMessage);
            chatData.chatHistoryData[to_username] = list;
            localStorage.setItem('chatData', JSON.stringify(chatData))
          }
        } else {
          let chatHistoryData = {}
          chatHistoryData[to_username] = [receiveMessage]
          localStorage.setItem('chatData', JSON.stringify({chatHistoryData}))
        }
        if (to_username == this.contactUser.customerId) {
          this.chatHistory.push(receiveMessage)
        }else{
          this.conversationListReadStatus[to_username] = true;
        }
        this.scrollToBottom();
        this.getConversationList();
      },
      // 发送文本消息
      sendTextMsg() {
        var text = document.querySelector('#inputcontent').value;
        let _this = this;
        if (!text) {
          this.$createDialog({
            type: 'alert',
            title: '温馨提示',
            content: '发送内容不能为空'
          }).show()
          return
        };
        var id = this.$imconn.getUniqueId()
        var msg = new WebIM.message('txt', id)
        let from_username = this.from_username
        let to_username = this.to_username
        let _thisChatHistory = this.chatHistory
        let sendTime = this.getNowTime()
        let fromNickName = this.fromNickName
        let fromHeadImg = this.fromHeadImg
        let toHeadImg = this.toHeadImg
        let toNickName = this.toNickName
        msg.set({
          msg: text,
          action: 'action',                     //用户自定义，cmd消息必填
          ext: {
            dataType: 'text',
            'fromNickName': fromNickName,
            'fromAvatar': fromHeadImg,
            'fromAccountType': this.fromAccountType,
            'toNickName': toNickName,
            'toAvatar': toHeadImg,
            'toAccountType': this.toAccountType
          },    //用户自扩展的消息内容（群聊用法相同）
          from: this.from_username,
          to: this.to_username,
          roomType: false,
          success: function (id, serverMsgId) {
            document.querySelector('#inputcontent').value = ''
            let sendMessage = {
              from: from_username,
              fromAvatar: fromHeadImg,
              fromNickName: fromNickName,
              sourceType: 'text',
              sourceMsg: text,
              time: sendTime
            }
            var chatData = JSON.parse(localStorage.getItem('chatData'))
            if (chatData) {
              if (chatData.chatHistoryData[to_username]) {
                chatData.chatHistoryData[to_username].push(sendMessage)
              } else {
                chatData.chatHistoryData[to_username] = [sendMessage]
              }
              localStorage.setItem('chatData', JSON.stringify(chatData))
            } else {
              let chatHistoryData = {}
              chatHistoryData[to_username] = [sendMessage]
              localStorage.setItem('chatData', JSON.stringify({chatHistoryData}))
            }
            _thisChatHistory.push(sendMessage)
            _this.scrollToBottom();
            _this.getConversationList();
            console.log('Send ')
          },
          fail: function (e) {
            console.log('Send private text error')
          }
        });
        msg.body.chatType = 'singleChat';
        this.$imconn.send(msg.body);
      },
      getNowTime() {
        let now = new Date()
        return now.getMonth() + 1 + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes()
      },
      // 获取url中的当前用户环信账号和聊天对象账号
      getParamsFromUrl() {
        var urlhash = location.hash //获取url中"?"符后的字串
        var theRequest = {}
        if (urlhash.indexOf('?') != -1) {
          var index = urlhash.indexOf('?') + parseInt(1)
          var str = urlhash.substr(index)
          var strArr = str.split('&')
          for (var i = 0; i < strArr.length; i++) {
            let arr = strArr[i].split('=')
            theRequest[arr[0]] = arr[1]
          }
        }
        return theRequest
      },

      toSendPic() {
        document.getElementById('picInput').click();
      },

      //发送图片
      sendPic() {
        var id = this.$imconn.getUniqueId()               // 生成本地消息id
        var msg = new WebIM.message('img', id);           // 创建图片消息
        var input = document.getElementById('picInput');  // 选择图片的input
        var file = WebIM.utils.getFileUrl(input);         // 将图片转化为二进制文件
        var allowType = {
          'jpg': true,
          'gif': true,
          'png': true,
          'bmp': true
        };
        let from_username = this.from_username
        let to_username = this.to_username
        let _thisChatHistory = this.chatHistory
        let sendTime = this.getNowTime()
        let fromNickName = this.fromNickName
        let fromHeadImg = this.fromHeadImg
        let toHeadImg = this.toHeadImg
        let toNickName = this.toNickName
        let imgUrl = ''
        if (file.filetype.toLowerCase() in allowType) {
          var option = {
            apiUrl: WebIM.config.apiURL,
            file: file,
            from: this.from_username,
            to: this.to_username,                  // 接收消息对象
            //action: 'action',                     //用户自定义，cmd消息必填
            ext: {
              'dataType': 'img',
              'fromNickName': fromNickName,
              'fromAvatar': fromHeadImg,
              'fromAccountType': this.fromAccountType,
              'toNickName': toNickName,
              'toAvatar': toHeadImg,
              'toAccountType': this.toAccountType
            },    //用户自扩展的消息内容（群聊用法相同）
            roomType: false,
            chatType: 'singleChat',
            onFileUploadError: function (a) {      // 消息上传失败
              console.log('onFileUploadError----' + JSON.stringify(a));
            },
            onFileUploadComplete: function (aa) {   // 消息上传成功
              console.log('onFileUploadComplete----' + JSON.stringify(aa));
              imgUrl = aa.uri + "/" + aa.entities[0].uuid;
            },
            success: function () {                // 消息发送成功
              console.log('Success');
              let sendMessage = {
                from: from_username,
                fromAvatar: fromHeadImg,
                fromNickName: fromNickName,
                sourceType: 'img',
                sourceMsg: imgUrl,
                width: 80,
                height: 80,
                time: sendTime
              }
              var chatData = JSON.parse(localStorage.getItem('chatData'))
              if (chatData) {
                if (chatData.chatHistoryData[to_username]) {
                  chatData.chatHistoryData[to_username].push(sendMessage)
                } else {
                  chatData.chatHistoryData[to_username] = [sendMessage]
                }
                localStorage.setItem('chatData', JSON.stringify(chatData))
              } else {
                let chatHistoryData = {}
                chatHistoryData[to_username] = [sendMessage]
                localStorage.setItem('chatData', JSON.stringify({chatHistoryData}))
              }
              _thisChatHistory.push(sendMessage)

            },
            flashUpload: WebIM.flashUpload
          };
          msg.set(option);
          // console.log(JSON.stringify(option));
          //msg.body.chatType = 'singleChat';
          this.$imconn.send(msg.body);
        }
      },
      // 单聊发送文件消息
      sendPrivateFile () {
        this.sendPic();
        return;
        var id = this.$imconn.getUniqueId()               // 生成本地消息id
        var msg = new WebIM.message('file', id);           // 创建图片消息
        var input = document.getElementById('picInput');  // 选择图片的input
        var file = WebIM.utils.getFileUrl(input);         // 将图片转化为二进制文件

        var allowType = {
          'jpg': true,
          'gif': true,
          'png': true,
          'bmp': true,
          'zip': true,
          'txt': true,
          'doc': true,
          'pdf': true
        };
        if (file.filetype.toLowerCase() in allowType) {
          var option = {
            apiUrl: WebIM.config.apiURL,
            file: file,
            from: this.from_username,
            to: this.to_username,                  // 接收消息对象
            roomType: false,
            chatType: 'singleChat',
            onFileUploadError: function () {      // 消息上传失败
              console.log('onFileUploadError');
            },
            onFileUploadComplete: function () {   // 消息上传成功
              console.log('onFileUploadComplete');
            },
            success: function () {                // 消息发送成功
              console.log('Success');
            },
            flashUpload: WebIM.flashUpload
          };
          msg.set(option);
          this.$imconn.send(msg.body);
        }
      },

      scrollToBottom(){
        console.log("//debugger ---- > scroll to bottom");
        let _this = this;
        this.$nextTick(() => {
          _this.$refs.contents.scrollTop = _this.$refs.contents.scrollHeight - _this.$refs.contents.clientHeight;
        });
      },

      closeChat(){
        this.$emit('closeChat','');
      },
      ImCardClick(status,id){
        this.detailStatus = status;
        switch (status) {
          case 2:
            this.$Get(this.$Config.api.goods, {
              goodsId: id
            }).then(res => {
              if (res.data != null) {
                this.goodsDetailInfo = res.data;
              }
            })
            break
        }
      },
      /*pastePic(e){
        if (e.clipboardData && e.clipboardData.types) {
          if (e.clipboardData.items.length > 0) {
            if (/^image\/\w+$/.test(e.clipboardData.items[0].type)) {
              var blob = e.clipboardData.items[0].getAsFile();
              var url = window.URL.createObjectURL(blob);
              var id = conn.getUniqueId();             // 生成本地消息id
              var msg = new WebIM.message('img', id);  // 创建图片消息
              msg.set({
                apiUrl: WebIM.config.apiURL,
                file: {data: blob, url: url},
                to: 'username',                      // 接收消息对象
                roomType: false,
                chatType: 'singleChat',
                onFileUploadError: function (error) {
                  console.log('Error');
                },
                onFileUploadComplete: function (data) {
                  console.log('Complete');
                },
                success: function (id) {
                  console.log('Success');
                }
              });
              conn.send(msg.body);
            }
          }
        }
      },*/
      //清空当前聊天记录
      clearChat() {

        localStorage.removeItem('chatData')
        this.chatHistory = []
      },
      // 选中一个表情 直接发送 不经过输入框直接发送
      clickFace(key) {
        var id = this.$imconn.getUniqueId()
        var msg = new WebIM.message('txt', id)
        let from_username = this.from_username
        let to_username = this.to_username
        let _thisChatHistory = this.chatHistory
        let sendTime = this.getNowTime()
        let fromNickName = this.fromNickName
        let fromHeadImg = this.fromHeadImg
        let toHeadImg = this.toHeadImg
        let toNickName = this.toNickName
        let _this = this;
        msg.set({
          msg: key,
          from: this.from_username,
          to: this.to_username,                  // 接收消息对象
          action: 'action',                     //用户自定义，cmd消息必填
          ext: {
            'dataType': 'emo',
            'fromNickName': fromNickName,
            'fromAvatar': fromHeadImg,
            'fromAccountType': this.fromAccountType,
            'toNickName': toNickName,
            'toAvatar': toHeadImg,
            'toAccountType': this.toAccountType
          },    //用户自扩展的消息内容（群聊用法相同）
          roomType: false,
          success: function (id, serverMsgId) {
            let sendMessage = {
              from: from_username,
              fromAvatar: fromHeadImg,
              fromNickName: fromNickName,
              sourceType: 'emo',
              sourceMsg: key,
              time: sendTime
              //nickName: myNickName
            }
            var chatData = JSON.parse(localStorage.getItem('chatData'))
            if (chatData) {
              if (chatData.chatHistoryData[to_username]) {
                chatData.chatHistoryData[to_username].push(sendMessage)
              } else {
                chatData.chatHistoryData[to_username] = [sendMessage]
              }
              localStorage.setItem('chatData', JSON.stringify(chatData))
            } else {
              let chatHistoryData = {}
              chatHistoryData[to_username] = [sendMessage]
              localStorage.setItem('chatData', JSON.stringify({chatHistoryData}))
            }
            _thisChatHistory.push(sendMessage)
            _this.scrollToBottom();
          },
          fail: function (e) {
            console.log('Send emoji text error')
          }
        })
        msg.body.chatType = 'singleChat'
        this.$imconn.send(msg.body)
      },
      hideEmoji() {
        this.showEmoji = false
      },
      handleMsg(item) {
        //if (this.emojiMap[item.sourceMsg]) {
        // console.log(JSON.stringify(item));

        var reg = /\[(.+?)\]/g;

        var res = item.sourceMsg.match(reg);

        if (res){
          for (let emoji in res){
            if(res[emoji] in this.emojiMap){
              item.sourceMsg = item.sourceMsg.replace(res[emoji],`<img src="${this.emojiMap[res[emoji]]}"/>`)
            }
          }
        }

        if (item.sourceType == 'emo') {
          //console.log("enter emoji  ---------"+item.sourceMsg)
          return `<img src="${this.emojiMap[item.sourceMsg]}"/>`
        } else if (item.sourceType == 'img') {
          //console.log("enter img  ---------" + item.sourceMsg)
          return `<img  width="80px" height="80px"  src="${item.sourceMsg}" />`
          //return `<img  width="80px" :height="(80 * item.height)/item.width"  src="${item.sourceMsg}" />`
        } else {
          //console.log("enter else ------------------" + item.sourceMsg)

          return item.sourceMsg
        }
      },
      chatWithId(id){
        this.to_username = id;
        this.detailStatus = 1;
        let _this = this;
        if (_this.to_username){
          this.$Get(this.$Config.api.customer, {
            customerId: this.to_username
          }).then(res => {
            _this.contactUser = res.data;
            sessionStorage.setItem("lastContactUser",res.data.customerId);
            _this.chatHistory = [];
            let hasHistory = false;
            for (let customer in _this.conversationList) {
              if (id == customer.customerId) {
                hasHistory = true;
              }
            }
            if (hasHistory){
            } else{
              var chatData = JSON.parse(localStorage.getItem('chatData'))
              if (chatData) {
                var currentChatData = chatData.chatHistoryData[_this.to_username];
                if (!currentChatData) {
                  chatData.chatHistoryData[_this.to_username] = [];
                }
                localStorage.setItem('chatData',JSON.stringify(chatData));
              }else{
                let chatHistoryData = {}
                chatHistoryData[to_username] = [sendMessage]
                localStorage.setItem('chatData', JSON.stringify({chatHistoryData}))
              }
            }
            _this.getChatListDataFromLocal();
          });
        }
      },
      getContactUserInfo(){

        let _this = this;
        if (this.to_username) {
          this.$Get(this.$Config.api.customer, {
            customerId: this.to_username
          }).then(res => {
            _this.contactUser = res.data;
            sessionStorage.setItem("lastContactUser",res.data.customerId);
          });
        }

      },

      isChatTextType(msg){
        return !(msg.ext && msg.ext.EXTRA_MY_MSG_TYPE) && msg.isPic != 1;
      },

      isUserCardType(msg){
        if (this.isChatTextType(msg)){
          return false
        } else{
          if (msg.ext && msg.ext.EXTRA_MY_MSG_TYPE) {
            if (msg.ext.EXTRA_MY_MSG_TYPE == "USER_CARD_MSG"){
              return true;
            }
          }
        }
        return false;
      },
      isGoodsCardType(msg){
        if (this.isChatTextType(msg)){
          return false
        } else{
          if (msg.ext && msg.ext.EXTRA_MY_MSG_TYPE) {
            if (msg.ext.EXTRA_MY_MSG_TYPE == "GOODS_HINT_MSG"){
              return true;
            }
          }
        }
        return false;
      },

      avatarClick(item){
        if (item.from != this.from_username)
        this.detailStatus = 1;
      }

    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  /*@import "../../assets/reset";*/
  /*@import "../../assets/functions";*/
  @import "../../assets/variables";
  @import "../../assets/mixins";
  /*!*聊天页面*!*/
  @import "../../assets/css/iconfont.css";

  html {
    font-size: 36px;
  }

  .chat{
    display: flex;
    display: -webkit-flex; /* Safari */
    width: 1060px;
    flex-direction: row;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    border-radius: 10px;
    box-sizing: border-box;
    box-shadow: darkgrey 10px 10px 30px 5px ;
  }
  .chat-left-content{
    display: flex;
    display: -webkit-flex; /* Safari */
    width: 250px;
    height: 600px;
    border-radius: 10px;
    background: #FFFFFF;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    flex-direction: column;
  }

  .chat-right-content{
    display: flex;
    display: -webkit-flex; /* Safari */
    flex-direction: column;
    width: 550px;
    height: 600px;
  }

  .chat-content{
    height: 420px;
    width: 550px;
    box-sizing: border-box;
  }

  .input-content{
    height: 180px;
    width: 550px;
    display: flex;
    display: -webkit-flex;
    flex-direction: column;

  }
  .name-label{
    width: 100%;
    height: 60px;
    display: flex;
    display: -webkit-flex; /* Safari */
    justify-content: center;
    align-items: center;
    background: #ffffff;
  }
  .msg-group-left{
    display: flex;
    display: -webkit-flex; /* Safari */
    flex-direction: row;
    justify-content: flex-start;

  }
  .msg-group-right{
    display: flex;
    display: -webkit-flex; /* Safari */
    flex-direction: row-reverse;
  }

  .text {
    display: inline-block;
    position: relative;
    padding: 0 10px;
    max-width: calc(100% - 40px);
    min-height: 30px;
    line-height: 2.5;
    font-size: 12px;
    text-align: left;
    word-break: break-all;
    background-color: #fafafa;
    border-radius: 4px;

    &:before {
      content: " ";
      position: absolute;
      top: 9px;
      right: 100%;
      border: 6px solid transparent;
      border-right-color: #fafafa;
    }
  }

  .text-right {
    display: inline-block;
    position: relative;
    padding: 0 10px;
    max-width: calc(100% - 40px);
    min-height: 30px;
    line-height: 2.5;
    font-size: 12px;
    text-align: right;
    word-break: break-all;
    background-color: #b2e281;
    border-radius: 4px;


    &:before {
      right: inherit;
      left: 100%;
      border-right-color: transparent;
      border-left-color: #b2e281;
    }
  }


  .input-txt {
    width: 100%;
    height: 120px;
    border: none;
    vertical-align: top;
    padding: 5px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
  }

  .btn-close{
    display: inline-block;
    *display: inline;
    *zoom: 1;
    vertical-align: top;
    font-size: 14px;
    line-height: 32px;
    cursor: pointer;
    cursor: hand;
    margin-left: 5px;
    padding: 0 20px;
    background-color: #5FB878;
    color: #fff;
    border-radius: 3px;
  }

  .action-label{
    display: flex;
    display: -webkit-flex; /* Safari */
    flex-direction: row;
    height: 30px;
  }

  .chat-ops-icon {
    @include font-dpr(20px);
    display: inline-block;
    padding: 0 10px;
    cursor: pointer;
  }

  .iconfont {
    @include font-dpr(16px);
  }

  .faces-ul {
    z-index: 1;
    position: absolute;
    width: 550px;
    height: 140px;
    left: 250px;
    bottom: 45px;
    border-radius: 2px;
    background: #fff;
    box-sizing: border-box;
    padding: 4px;
    box-shadow: rgba(0, 0, 0, 0.1) 0 4px 6px 0;
    .webim-emoji-item {
      cursor: pointer;
      display: inline-block;
      margin: 2px 3px 0 3px;
      width: px2rem(35px);
      height: px2rem(35px);
      line-height: 1;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .chat-detail-content{
    width: 260px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    border-left: #dddedf 1px solid;
    display: flex;
    display: -webkit-flex; /* Safari */
    flex-direction: column;
    border-bottom-right-radius: 10px;
  }

  .chat-detail-title{
    width: 100%;
    height: 60px;
    align-items: center;
    justify-content: center;
    display: flex;
    display: -webkit-flex; /* Safari */
    flex-direction: row;
    div{
      display: flex;
      display: -webkit-flex; /* Safari */
      flex-direction: column;
      color: #54bb00;

      p{
        flex-grow: 1;
      }

      span{
        height: 2px;
        width: 100%;
        background: #54bb00;
      }
    }
  }

  .item-user-detail{
    display: flex;
    height: 100%;
    display: -webkit-flex; /* Safari */
    flex-direction: column;
    background: #f6f7f8;
    border-bottom-right-radius: 10px;
    align-items: center;
  }

  .item-avatar{
    width: 100px;
    height: 100px;
    margin-top: 10px;
    border-radius: 50%;
  }
  .item-goods{
    width: 220px;
    height: 220px;
    margin-top: 10px;
  }

  .info-item{
    width: 240px;
    margin-top: 10px;
    height: 30px;
    display: flex;
    display: -webkit-flex; /* Safari */
    flex-direction: row;
    color: #333333;
  }

  .goods-item{
    width: 240px;
    margin-top: 10px;
    height: 20px;
    display: flex;
    display: -webkit-flex; /* Safari */
    flex-direction: row;
    color: #333333;
  }
  .item-value{
    flex-grow: 1;
    text-align: right;
    color: #888888;
  }

  .user-card{
    background: white;
    width: 40%;
    height: 40px;
  }
  .goods-card{
    display: flex;
    display: -webkit-flex; /* Safari */
    flex-direction: column;
    background: white;
    height: 120px;
    width: 240px;
    border-radius: 8px;
    cursor: pointer;
  }

  .goods-card-content{
    display: flex;
    display: -webkit-flex; /* Safari */
    flex-direction: row;
    width: 100%;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    padding: 10px;
    height: 90px;

    img{
      width: 60px;
      height: 60px;
      border-radius: 4px;
    }
  }

  .user-item-normal{
    background: #FFFFFF;
  }

  .user-item-checked{
    background: #f5f6f7;
  }



</style>
